package com.zcc.servlet;

import com.sun.deploy.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//                首先要获取下载文件的路径，用String变量储存地址
        String realpath = "D:\\mavenproject\\javaweb\\response\\src\\main\\resources\\1.png";
        System.out.println("下载路径:"+realpath);
//                获取下载的文件名，lastIndexOf和+1就是获取以后一个"/"的下一个字符串
        String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
//                设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西，下载文件响应头，用URLEncoder.encode()来给文件转码，防止中文名乱码
        resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8"));
//                获取下载文件的输入流，把文件地址作为参数，建立数据流对象
        FileInputStream fis = new FileInputStream(realpath);
//                创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
//                获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
//                将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
        while ((len = fis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
//                流关闭
        fis.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
